# -*- coding=utf-8 -*-

"""
mongodb model base
"""
from framework.model import Model
import pymongo
from config.cfg import db_cfg

class MongoModel(Model):
    """
    mongo db model base
    """
    db = None  # mongo db object
    current_db = None  # mongo db name
    current_client = None  # mogo db connection
    default = False
    collection = None

    def __init__(self, **kwargs):
        """
        init
        """
        super(MongoModel, self).__init__(**kwargs)
        if not self.load_db():
            raise pymongo.errors.ConfigurationError("load mongo db error")


    def load_db(self, name="default"):
        """
        from config load mongo db
        :param name: confing mongodb connection name
        :return: bool
        """
        if isinstance(db_cfg, tuple):
            for item in db_cfg:
                if isinstance(item, dict):
                    if "name" in item.keys() and "type" in item.keys():
                        if item.get("type") == 'mongo':
                            if name == 'default' and item.get("default"):
                                if self.default:
                                    return True

                                self.current_db = item.get("name")
                                self.default = True

                            if item.get("name") == name:
                                if self.current_db == name:
                                    return True

                                self.current_db = name
                                self.default = False

                            self.current_client = pymongo.MongoClient(item.get('host'), item.get('port'))
                            try:
                                self.db = self.current_client[item.get('db')]
                                self.collection = self.db[self.get_collection()]
                                self.__table__ = self.get_collection()
                            except TypeError:
                                raise TypeError(r"mongodb reutrn failure")
                            return True

        return False

    def get_collection(self):
        """
        
        :return: 
        """
        return 'collection_name'

    def find_one(self, where):
        """
        
        :param where: 
        :return: 
        """
        if not isinstance(where, dict):
            return None

        u = self.collection.find_one(where)
        if not u:
            return None
        return self.__class__(**u)

    def save(self):
        """
        save to 
        :return: 
        """
        return self.collection.save(self)

    def update(self):
        """
        update
        :return: 
        """
        return self.collection.update({"_id": self.get("_id")}, self)

    def insert(self):
        """
        insert mongodb
        :return: 
        """
        return self.collection.insert(self)